package com.seekprice.core.impl;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.seekprice.constant.Constant;
import com.seekprice.core.Extractor;
import com.seekprice.core.Product;

public class NeweggExtractor implements Extractor {
	
	private static Logger logger = LoggerFactory.getLogger(NeweggExtractor.class);
    
	public List<Product> search(String key) {
		logger.debug("查询关键字为:'{}'",key);
		try {
			Document doc = Jsoup
					.connect(Constant.NEWEGG_URL+key)
					.userAgent(Constant.USERAGENT)
					.timeout(Constant.TIMEOUT).post();
			Elements resultList = doc.select("#itemGrid1");
			Elements productList = resultList.select("div.itemCell");
			
			List<Product> seekResult=new ArrayList<Product>();
			
			for (int i = 0; i < productList.size(); i++) {
				Element product = productList.get(i);
				Element productInfo=product.getElementsByTag("dl").first();
				String title = productInfo.select("dd.pdInfo").first().select("p.info").first().select("a[href]").first().text();
				if (title.contains(key) == false) {
					continue;
				}
				String url = productInfo.select("dd.pdInfo").first().select("p.info").first().select("a[href]").first().attr("href");
				String price = productInfo.select("dd.price").first().select("strong.price").first().text();
				String evaluateUrl = productInfo.select("dd.rank").select("a[href]").first().attr("href");
				String evaluateQuantity = productInfo.select("dd.rank").select("a[href]").first().text();
				String img = productInfo.select("dt").select("a[href]").first().select("img").first().attr("src");
				
				Product entity=new Product();
				entity.setShop("新蛋商城");
				entity.setTitle(title);
				entity.setPrice(price);
				entity.setUrl(url);
				entity.setImg(img);
				entity.setEvaluateQuantity(evaluateQuantity);
				entity.setEvaluateUrl(evaluateUrl);
				seekResult.add(entity);
			}
			return seekResult;
		} catch (Exception e) {
			logger.error("解析出错!",e);
		}
		return java.util.Collections.emptyList();
	}
}
